import { endTrack, startTrack } from '@/api/tracking'
import { cameraList } from '@/shared'
import { useCarStore } from '@/stores/car'
import { ElMessage } from '@/stores/elMessage'
import { useVideoStore } from '@/stores/video'
import { i18n, initWebSocket } from '@/utils'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { postTrackingState, getTrackingState as trackingStateApi } from '../api/control'
import { useCarRelevant } from './useCarRelevant'

export const useTracking = defineStore('tracking', () => {
  const visible = ref(false)
  let ws: WebSocket | null = null
  const list = ref<{ trackingName: string; trackingId: number }[]>([])
  const car = useCarStore()
  const isTrackingId = ref<number | null>(null)
  const video = useVideoStore()
  const carRelevant = useCarRelevant()
  function showDrawer() {
    visible.value = true
    connectWS()
    showVideo()
  }

  function connectWS() {
    ws = initWebSocket('/websocket/patroling/tracking', {
      onmessage: onMessage
    })
  }

  function onMessage(e: { data: string }) {
    const wsData = JSON.parse(e.data)
    list.value = wsData.data
  }

  function getWS() {
    return ws
  }

  function closeDrawer() {
    visible.value = false
    closeWS()
  }

  function closeWS() {
    if (ws) {
      ws.close()
      ws = null
    }
  }

  function selectTarget(val: number) {
    isTrackingId.value = val
    startTrack(car.currentCar, val)
    showVideo()
  }

  function showVideo() {
    const webrtcUrl = cameraList.value.find((item) => item.name === '目标跟踪')?.rtsp
    if (webrtcUrl) {
      video.changeVideo(webrtcUrl)
    } else {
      ElMessage({
        type: 'error',
        message: i18n.global.t('mei-you-guan-lian-dui-ying-shi-pin-liu')
      })
    }
  }

  function cancelTracking() {
    isTrackingId.value = null
    endTrack(car.currentCar)
    video.changeVideo('')
  }

  const trackingState = ref(0)

  async function getTrackingState() {
    const res = await trackingStateApi(car.currentCar)
    trackingState.value = res.data
    if (trackingState.value === 0) {
      visible.value = true
    } else {
      visible.value = false
    }
  }

  async function changeTrackingState(value: 0 | 1 | -1) {
    trackingState.value = value
    carRelevant.visible = false
    if (trackingState.value === 0) {
      visible.value = true
    } else {
      visible.value = false
    }
    await postTrackingState(car.currentCar, value)
    setTimeout(() => {
      getTrackingState()
    }, 1000)
  }

  return {
    visible,
    showDrawer,
    getWS,
    closeDrawer,
    onMessage,
    list,
    selectTarget,
    cancelTracking,
    isTrackingId,
    /**
     * 自动跟踪状态
     */
    trackingState,
    /**
     * 获取自动跟踪状态
     */
    getTrackingState,
    /**
     * 修改自动跟踪状态
     */
    changeTrackingState
  }
})
